package com.sfh.appversion.controller;

import ch.qos.logback.core.util.FileUtil;
import com.sfh.appversion.base.Result;
import com.sfh.appversion.dao.entity.PhoneTypeDO;
import com.sfh.appversion.dto.req.UseDelReqDTO;
import com.sfh.appversion.dto.req.UseNewReqDTO;
import com.sfh.appversion.dto.req.UseReqDTO;
import com.sfh.appversion.server.UserServer;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/***
 * 用户
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServer userServer;


    @PostMapping("login")
    public Result login(@RequestBody UseReqDTO req) {
        //登录
        return Result.success(userServer.login(req));
    }

    @GetMapping("queryPhoneType")
    public Result<List<PhoneTypeDO>> queryPhoneType(@PathVariable String phoneType) {
        //登录
        return Result.success(userServer.queryPhoneType(phoneType));
    }


    @PostMapping("add")
    public Result add(@RequestBody UseNewReqDTO req) {
        //添加用户
        return Result.success(userServer.addUser(req));
    }

    @PostMapping("del")
    public Result del(@RequestBody UseDelReqDTO req) {
        //删除用户
        return Result.success(userServer.delUser(req.getUserId()));
    }

    @PostMapping("queryListUser")
    public Result queryListUser() {
        //全部用户信息列表
        return Result.success(userServer.queryList());
    }

    @PostMapping("queryAllConfig")
    public Result queryAllConfig() {
        //全部配置项列表
        return Result.success(userServer.queryAllConfig());
    }

    @PostMapping("queryConfig")
    public Result queryConfig(@RequestParam(value = "configKey") String configKey) {
        // 查询配置项
        return Result.success(userServer.queryConfig(configKey));
    }

    //配置的文件存储绝对路径
    @Value("${file.uploadFolder}")
    String fileSavePath;


    @PostMapping("file")
    public Result file(@RequestParam("file") MultipartFile file) {
        // 查询配置项
        if (file.isEmpty()) {
            return Result.create("201", "文件上传失败");
        }


        File pareFIle = new File(System.getProperty("user.dir"),fileSavePath);
        if (!pareFIle.exists()) {
            pareFIle.mkdirs();
        }
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();//生成文件名
        try {
            file.transferTo(new File(pareFIle, fileName));
            return Result.create("200", "文件上传成功", fileName);

        } catch (Exception e) {
            System.out.println("文件上传异常" + e.getLocalizedMessage());

            return Result.create("202", "文件上传失败");
        }

    }

    @GetMapping(value = "/img/{name}")
    public void look(HttpServletResponse res, @PathVariable String name) {

        File pareFIle = new File(System.getProperty("user.dir"),fileSavePath);
        if (pareFIle.exists()){

            OutputStream os = null;
            try {
                File src = new File(pareFIle,name);
                if (src.exists()) {
                    // 查询配置项
                    res.setHeader("content-type", "application/octet-stream");
                    res.setContentType("application/octet-stream");
                    res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));

                    os = res.getOutputStream();
                    FileCopyUtils.copy(new FileInputStream(src), os);
                }

            } catch (Exception e) {

            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (Exception e) {
                    }
                }
            }

        }
    }
}
